﻿namespace EFS.RC.CommunicatorContext.Common
{
	public partial class PlaySound : EFS.RC.CommunicatorContext.Common.Pages.Controls.Control
	{
		#region Locals
		/// fileData
		private System.Byte[] fileData = null;

		/// fileDataStream
		private System.IO.MemoryStream fileDataStream = null;

		/// repeatCount
		private System.Int32? repeatCount = null;

		/// repeatIndex
		private System.Int32 repeatIndex = 0;

		/// popupMessage
		private System.String popupMessage = null;
		#endregion

		#region Constructors
		/// Implicit
		public PlaySound()
		{
			InitializeComponent();
		}

		///// Implicit
		//public PlaySound(System.IO.Stream fileStream)
		//{
		//	// check
		//	EFS.Common.Verify.Reference(fileStream, "fileStream");

		//	// set
		//	System.IO.StreamReader sr = new System.IO.StreamReader(fileStream);
		//	using (System.IO.MemoryStream ms = new System.IO.MemoryStream(fileStream))
		//	{
		//		this.fileData = ms;
		//	}
		//}
		#endregion

		/// Play
		public void Play(
			System.Byte[] fileData,
			System.Int32? repeatCount = null,
			System.String popupMessage = null)
		{
			if (null != this.fileDataStream)
			{
				return;
			}

			// check
			EFS.Common.Verify.Reference(fileData, "fileData");

			// set
			this.fileData = fileData;
			this.repeatCount = repeatCount;
			this.popupMessage = popupMessage;

			// play
			PlayInternal();
		}

		/// PlayInternal
		private void PlayInternal()
		{
			// stop if plaiyng previous
			this.mediaElement.Stop();

			// make new
			this.fileDataStream = new System.IO.MemoryStream(fileData);
			this.mediaElement.AutoPlay = true;
			this.mediaElement.SetSource(fileDataStream);
			this.mediaElement.Position = System.TimeSpan.Zero;
		}

		/// Stop
		public void Stop()
		{
			Reset();

			repeatIndex = 0;
		}

		/// Reset
		private void Reset()
		{
			if (null == this.fileDataStream)
			{
				return;
			}

			this.mediaElement.Stop();
			this.fileDataStream.Close();
			this.fileDataStream = null;
		}

		private void mediaElement_CurrentStateChanged(object sender, System.Windows.RoutedEventArgs e)
		{
		}

		/// Ended playing
		private void mediaElement_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
		{
			Reset();

			// increment as it competed playing
			++repeatIndex;

			// test
			if (EFS.Common.Functions.Nullable<System.Int32>.GetSafe(this.repeatCount, 0) > repeatIndex)
			{
				PlayInternal();
			}
			else
			{
				if (EFS.Common.Verify.String(popupMessage))
				{
					ShowSuccessMessage(popupMessage);
				}
			}
		}
	}

}